package com.commerce.order.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;

/**
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {

    // 产品服务交换机
    public static final String PRODUCT_EXCHANGE = "product.exchange";
    
    // 获取产品详情队列
    public static final String PRODUCT_GET_QUEUE = "product.get.queue";
    public static final String PRODUCT_GET_ROUTING_KEY = "product.get";
    
    // 获取产品详情结果队列
    public static final String PRODUCT_GET_RESULT_QUEUE = "product.get.result.queue";
    public static final String PRODUCT_GET_RESULT_ROUTING_KEY = "product.get.result";

    @Bean
    public DirectExchange productExchange() {
        return ExchangeBuilder
                .directExchange(PRODUCT_EXCHANGE)
                .durable(true)
                .build();
    }

    @Bean
    public Queue productGetQueue() {
        return QueueBuilder
                .durable(PRODUCT_GET_QUEUE)
                .build();
    }

    @Bean
    public Queue productGetResultQueue() {
        return QueueBuilder
                .durable(PRODUCT_GET_RESULT_QUEUE)
                .build();
    }

    @Bean
    public Binding bindingProductGet() {
        return BindingBuilder.bind(productGetQueue())
                .to(productExchange())
                .with(PRODUCT_GET_ROUTING_KEY);
    }

    @Bean
    public Binding bindingProductGetResult() {
        return BindingBuilder.bind(productGetResultQueue())
                .to(productExchange())
                .with(PRODUCT_GET_RESULT_ROUTING_KEY);
    }
    
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    
    @Bean
    @Primary
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, ObjectProvider<Jackson2JsonMessageConverter> converterProvider) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        converterProvider.ifAvailable(rabbitTemplate::setMessageConverter);
        
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                System.err.println("消息发送失败：" + cause);
            }
        });
        
        rabbitTemplate.setReturnsCallback(returned -> {
            System.err.println("消息被退回：" + returned.getMessage());
        });
        
        return rabbitTemplate;
    }

    @Bean
    @Primary
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
            ConnectionFactory connectionFactory, 
            ObjectProvider<Jackson2JsonMessageConverter> converterProvider) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        converterProvider.ifAvailable(factory::setMessageConverter);
        factory.setAutoStartup(true);
        factory.setMissingQueuesFatal(false);
        factory.setConcurrentConsumers(1);
        factory.setMaxConcurrentConsumers(1);
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
        factory.setReceiveTimeout(1000L);
        factory.setBatchReceiveTimeout(5000L);
        return factory;
    }
} 